package com.hangzhou.xyj.ui.activity;

import android.os.AsyncTask;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.GroupModel;
import com.hangzhou.xyj.model.MyGroupModel;
import com.hangzhou.xyj.net.handler.GetGroupsInfoHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.request.GetGroupsInfoReq;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.adapter.MyGroupAdapter;
import com.hangzhou.xyj.ui.listener.RecycleOnItemClickListener;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView;
import com.hangzhou.xyj.ui.widget.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yaohuix on 2016/1/11.
 */
public class MyGroupActivity extends BaseActivity {
    private RecyclerView mRecyclerView;
    private StickyRecyclerHeadersDecoration mHeaderAdapter;
    private MyGroupAdapter mAdapter;
    private List<MyGroupModel> mGroupModels;

    @Override
    public void initTop() {
        enableTitle(true, "我的圈子");
        enableRightNav(true, R.drawable.ic_publish);
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_mygroup);
    }

    @Override
    public void initViews() {
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_my_group);
        mAdapter = new MyGroupAdapter(this, mGroupModels);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter);
        // Add the sticky headers decoration
        mHeaderAdapter = new StickyRecyclerHeadersDecoration(mAdapter);
        mRecyclerView.addItemDecoration(mHeaderAdapter);
        mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                mHeaderAdapter.invalidateHeaders();
            }
        });
    }

    @Override
    public void initDatas() {
        loadData();
    }

    @Override
    public void initListeners() {
        //添加点击item监听器
        mAdapter.setOnRecyclerViewItemClickListener(new RecycleOnItemClickListener<MyGroupModel>() {
            @Override
            public void onItemClick(View view, MyGroupModel model) {
                if (model != null) {
                    IntentManager.getInstance().goChatActivity(mContext, model.getGroupCode(), EaseConstant.CHATTYPE_GROUP);
                }
            }
        });
        setOnNavRightListener(new CommonTitleBarView.OnNavRightListener() {
            @Override
            public void onNavRight() {
                if (!isLogin()) {
                    return;
                }
                IntentManager.getInstance().goAddGroupActivity(mContext);
            }
        });
    }

    private void loadData() {
        //获取服务器的群组信息
        new AsyncTask<Void, Void, List<EMGroup>>() {

            @Override
            protected List<EMGroup> doInBackground(Void... params) {
                List<EMGroup> groupList = null;
                try {
                    groupList = EMClient.getInstance().groupManager().getJoinedGroupsFromServer();//
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                return groupList;
            }

            @Override
            protected void onPostExecute(List<EMGroup> emGroups) {
                super.onPostExecute(emGroups);
                if (emGroups == null || emGroups.size() <= 0) {
                    setNoDataTip(true, "暂无数据哦~");
                    return;
                }

                //群组id数组
                String[] ids = new String[emGroups.size()];

                for (int i = 0; i < emGroups.size(); i++) {
                    EMGroup emGroup = emGroups.get(i);
                    ids[i] = emGroup.getGroupId();
                }
                //批量获取群组详情
                getGroupDetail(ids);

            }
        }.execute();
    }

    /**
     * 获取群组信息
     */
    private void getGroupDetail(final String... groupIds) {
        GetGroupsInfoReq req = new GetGroupsInfoReq(groupIds);
        HttpLoader.getInstance().sendRequest(new GetGroupsInfoHandler(req, new MyHttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
//                if (model == null) {
//                    setNoDataTip(true, "暂时没有数据哦~");
//                    return;
//                }
                List<GroupModel> groupModels = (List<GroupModel>) model;

                List<MyGroupModel> tempList = new ArrayList<>();
                MyGroupModel groupModel;
                for (int i = 0; i < groupModels.size(); i++) {
                    GroupModel serverGroup = groupModels.get(i);
                    groupModel = new MyGroupModel();

                    groupModel.setId(serverGroup.getId());
                    groupModel.setGroupCode(serverGroup.getGroupCode());
                    groupModel.setGroupImage(serverGroup.getGroupImage());
                    groupModel.setGroupName(serverGroup.getGroupName());
                    groupModel.setGroupDesc(serverGroup.getGroupDesc());

                    String userId = XYJApplication.getUserInfo().getUserId();
                    if (serverGroup.getGroupMasterId().equals(userId)) { //群主id是自己，则为自己创建的
                        groupModel.setGroupType(MyGroupModel.CREATE_GROUP);
                    } else {
                        groupModel.setGroupType(MyGroupModel.ENTER_GROUP);
                    }
                    tempList.add(groupModel);
                }

                if (mGroupModels == null) {
                    mGroupModels = new ArrayList<>();
                }
                //先过滤出自己的创建的圈子
                for (MyGroupModel tempModel : tempList) {
                    if (tempModel.getGroupType() == MyGroupModel.CREATE_GROUP) {
                        mGroupModels.add(tempModel);
                    }
                }

                //再过滤出我加入的圈子
                for (MyGroupModel tempModel : tempList) {
                    if (tempModel.getGroupType() == MyGroupModel.ENTER_GROUP) {
                        mGroupModels.add(tempModel);
                    }
                }
                //更新UI
//                if (mGroupModels.size() == 0) {
//                    setNoDataTip(true, "暂无数据~");
//                } else {
                mAdapter.update(mGroupModels);
//                }
            }
        }, 0));
    }
}
